package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
@EnableConfigurationProperties(MinioProperties.class)
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioProperties minio;
    @Autowired
    private MinioClient minioClient;

    @Override
    public String fileUpload(MultipartFile file) {
        try {
            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minio.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minio.getBucketName()).build());
            } else {
                System.out.println("Bucket '" + minio.getBucketName() + "' already exists.");
            }

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.

            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String date = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            String newfileName = date + "/" + uuid + "_" + fileName;

            InputStream inputStream = file.getInputStream();
            PutObjectArgs build = PutObjectArgs.builder()
                    .bucket(minio.getBucketName())
                    .object(newfileName)
                    .stream(inputStream, inputStream.available(), -1)
                    .build();

            //上传图片
            minioClient.putObject(build);
            //http://192.168.178.133:9000/lease/chuishi.jpg
            String url = minio.getEndpoint() + "/" + minio.getBucketName() + "/" + newfileName;
            return url;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        }
        return null;
    }
}
